package com.tuling.jucdemo.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author :tangweiliang
 * @date : 2022/11/17 22:07
 * 未来的你会感谢现在努力的自己
 *
 * 非公平
 */
@Slf4j
public class ReentrantLockDemo5 {
    public static void main(String[] args) throws InterruptedException {
        //ReentrantLock lock = new ReentrantLock();//默认是非公平 目的是提高效率
        ReentrantLock lock = new ReentrantLock(true); //公平
        for (int i = 0; i < 500; i++) {
            new Thread(()->{
                lock.lock();
                try{
                    try {
                        Thread.sleep(10);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    log.debug(Thread.currentThread().getName() + " running...... ");
                }finally {
                    lock.unlock();
                }
            },"t" + i).start();
        }

        //1s之后去竞争
        Thread.sleep(1000);

        for (int i = 0; i < 500; i++) {
            new Thread(()->{
                lock.lock();
                try{
                    log.debug(Thread.currentThread().getName() + " ruunning..... ");
                }finally {
                    lock.unlock();
                }
            },"强行插入" + i).start();
        }
    }
}
